package com.syas.web.controllers;

import com.syas.common.exception.EntityOperateException;
import com.syas.common.exception.ExcelException;
import com.syas.common.exception.ValidatException;
import com.syas.common.utilities.ExcelUtils;
import com.syas.common.utilities.PageListUtil;
import com.syas.model.models.AttendInfo;
import com.syas.model.models.Fmger;
import com.syas.service.interfaces.IAttendInfoService;
import com.syas.service.interfaces.IFmgerService;
import com.syas.web.auth.AuthPassport;
import com.syas.web.models.FmgerEditModel;
import com.syas.web.models.FmgerSearchModel;
import com.syas.web.models.extension.FmgerModelExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/orgfrmger")
public class FmgerController extends BaseController {
	
	@Autowired
    @Qualifier("FmgerService")
    private IFmgerService fmgerService;

    @Autowired
    @Qualifier("AttendInfoService")
    private IAttendInfoService attendInfoService;

    //excel的sheet名称
    private  static final  String SHEETNAME = "Sheet1";
    //excel的总列数
    private  static final  int COLCNT = 28;
    private  static final  int COLCNT_A = 8;

    @AuthPassport
	@RequestMapping(value="/emplist", method = {RequestMethod.GET})
    public String list(HttpServletRequest request, Model model, FmgerSearchModel searchModel){
        model.addAttribute("requestUrl", request.getServletPath());
        model.addAttribute("requestQuery", request.getQueryString());
        model.addAttribute("searchModel", searchModel);
        int pageNo = ServletRequestUtils.getIntParameter(request, PageListUtil.PAGE_NO_NAME, PageListUtil.DEFAULT_PAGE_NO);
        int pageSize = ServletRequestUtils.getIntParameter(request, PageListUtil.PAGE_SIZE_NAME, PageListUtil.DEFAULT_PAGE_SIZE);
        model.addAttribute("contentModel", fmgerService.listPage(searchModel.getName(),
                searchModel.getEzubouname(),
                searchModel.getMobileno(),
                searchModel.getCertid(),
                pageNo,
                pageSize));
        return "orgfrmger/emplist";
    }
    @AuthPassport
    @RequestMapping(value = "/edit/{id}", method = {RequestMethod.POST})
    public String edit(HttpServletRequest request, Model model, @Valid @ModelAttribute("contentModel") FmgerEditModel editModel, @PathVariable(value="id") Integer id, BindingResult result) throws EntityOperateException, ValidatException {
        if(result.hasErrors())
            return edit(request, model, id);
        String returnUrl = ServletRequestUtils.getStringParameter(request, "returnUrl", null);
        Fmger fmger = FmgerModelExtension.toFmger(editModel);
        fmgerService.update(fmger);
        if(returnUrl==null)
            returnUrl="orgfrmger/emplist";
        return "redirect:"+returnUrl;
    }

    @AuthPassport
    @RequestMapping(value = "/edit/{id}", method = {RequestMethod.GET})
    public String edit(HttpServletRequest request, Model model, @PathVariable(value="id") Integer id) throws ValidatException{
        if(!model.containsAttribute("contentModel")){
            FmgerEditModel fmgerEditModel=FmgerModelExtension.toFmgerEditModel(fmgerService.get(id));
            model.addAttribute("contentModel", fmgerEditModel);
        }
        return "orgfrmger/edit";
    }

    @AuthPassport
    @RequestMapping(value = "/add", method = {RequestMethod.GET})
    public String add(HttpServletRequest request){
        return "orgfrmger/edit";
    }

    @AuthPassport
    @RequestMapping(value = "/delete/{id}", method = {RequestMethod.GET})
    public String delete(HttpServletRequest request, Model model, @PathVariable(value="id") Integer id) throws ValidatException, EntityOperateException{
        fmgerService.delete(id);
        String returnUrl = ServletRequestUtils.getStringParameter(request, "returnUrl", null);
        if(returnUrl==null)
            returnUrl="authority/chain";
        return "redirect:"+returnUrl;
    }

    @AuthPassport
    @RequestMapping(value="/emplist", method = {RequestMethod.POST})
    public void excelToDb(HttpServletRequest request, Model model){
        try {
            // 转型为MultipartHttpRequest
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> fileList = multipartRequest.getFiles("excelFileUpload");
            String suffix = "";
            for (MultipartFile mf : fileList) {
                if(!mf.isEmpty()){
                    List<Fmger> list = new ArrayList<Fmger>();
                    suffix =  mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."),mf.getOriginalFilename().length());
                    //导入到数据库
                    LinkedHashMap<String,String> hashMap = new LinkedHashMap<String,String>();
                    toHashMap(hashMap);
                    if(".xls".equals(suffix)){
                        list = ExcelUtils.excelToList(mf.getInputStream(),
                                SHEETNAME,
                                Fmger.class,
                                hashMap
                        );
                    }else if ((".xlsx").equals(suffix)){
                        list = ExcelUtils.excelToListByXSSF(mf.getInputStream(),
                                SHEETNAME,
                                Fmger.class,
                                hashMap,
                                COLCNT
                        );
                    }else {
                         throw new ExcelException("文件格式错误！");
                    }
                    //先删除原来的数据
                    fmgerService.delete();
                    if(list != null && list.size() >0 ){
                        for (Fmger fmger:list){
                            fmgerService.save(fmger);
                        }
                    }
                }
            }
            model.addAttribute("result","导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("result","导入失败");
        }
        list(request,model,new FmgerSearchModel());
    }

    @AuthPassport
    @RequestMapping(value="/attendlist", method = {RequestMethod.GET})
    public String attendList(HttpServletRequest request, Model model, FmgerSearchModel searchModel){
        model.addAttribute("requestUrl", request.getServletPath());
        model.addAttribute("requestQuery", request.getQueryString());
        model.addAttribute("searchModel", searchModel);
        int pageNo = ServletRequestUtils.getIntParameter(request, PageListUtil.PAGE_NO_NAME, PageListUtil.DEFAULT_PAGE_NO);
        int pageSize = ServletRequestUtils.getIntParameter(request, PageListUtil.PAGE_SIZE_NAME, PageListUtil.DEFAULT_PAGE_SIZE);
        model.addAttribute("contentModel", attendInfoService.listPage(searchModel.getName(),
                searchModel.getCertid(),
                pageNo,
                pageSize));
        return "orgfrmger/attendlist";
    }

    @AuthPassport
    @RequestMapping(value="/attendlist", method = {RequestMethod.POST})
    public void attendExcelToDb(HttpServletRequest request, Model model){
        try {
            // 转型为MultipartHttpRequest
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> fileList = multipartRequest.getFiles("excelFileUpload");
            String suffix = "";
            for (MultipartFile mf : fileList) {
                if(!mf.isEmpty()){
                    List<AttendInfo> list = new ArrayList<AttendInfo>();
                    suffix =  mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."),mf.getOriginalFilename().length());
                    //导入到数据库
                    LinkedHashMap<String,String> hashMap = new LinkedHashMap<String,String>();
                    toAttendHashMap(hashMap);
                    if(".xls".equals(suffix)){
                        list = ExcelUtils.excelToList(mf.getInputStream(),
                                SHEETNAME,
                                AttendInfo.class,
                                hashMap
                        );
                    }else if ((".xlsx").equals(suffix)){
                        list = ExcelUtils.excelToListByXSSF(mf.getInputStream(),
                                SHEETNAME,
                                AttendInfo.class,
                                hashMap,
                                COLCNT_A
                        );
                    }else {
                        throw new ExcelException("文件格式错误！");
                    }
                    //先删除原来的数据
                    attendInfoService.delete();
                    if(list != null && list.size() >0 ){
                        for (AttendInfo attendInfo:list){
                            attendInfoService.save(attendInfo);
                        }
                    }
                }
            }
            model.addAttribute("result","导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("result","导入失败");
        }
        attendList(request, model, new FmgerSearchModel());
    }

    /**
     * @param hashMap ：excel表头和字段属性名字的hashmap集合
     * @return
     * @MethodName : toHashMap
     * @Description : 员工基础信息的对应
     */
    private void toHashMap(LinkedHashMap<String,String> hashMap){
        hashMap.put("姓名*","realName");
        hashMap.put("身份证号码*","certId");
        hashMap.put("一级部门*","departmentLevel1");
        hashMap.put("二级部门*","departmentLevel2");
        hashMap.put("三级部门*","departmentLevel3");
        hashMap.put("四级部门*","departmentLevel4");
        hashMap.put("五级部门*","departmentLevel5");
        hashMap.put("六级部门*","departmentLevel6");
        hashMap.put("岗位*","postType");
        hashMap.put("级别","level");
        hashMap.put("入职日期","joinDate");
        hashMap.put("实际转正时间*","realemployeeDate");
        hashMap.put("离职时间*","leaveDate");
        hashMap.put("当月绩效工资标准","salaryBase");
        hashMap.put("人员类别*","empType");
        hashMap.put("在职状态*","empStatus");
        hashMap.put("城市类别*","cityType");
        hashMap.put("职能类别*","functionType");
        hashMap.put("是否筹建期*","isBuilding");
        hashMap.put("工作地（市）*","workPlace");
        hashMap.put("员工e租宝账号*","ezboUname");
        hashMap.put("直属领导*","leaderName");
        hashMap.put("直属领导e租宝账号*","leaderEzboUname");
        hashMap.put("到岗日期","workStartdate");
        hashMap.put("离岗日期","workLeavedate");
    }
    /**
     * @param hashMap ：excel表头和字段属性名字的hashmap集合
     * @return
     * @MethodName : toAttendHashMap
     * @Description : 出勤表的对应
     */
    private void toAttendHashMap(LinkedHashMap<String,String> hashMap){
        hashMap.put("身份证号码","certId");
        hashMap.put("姓名","name");
        hashMap.put("岗位","station");
        hashMap.put("入职时间","intime");
        hashMap.put("离职时间","outtime");
        hashMap.put("应出勤天数*","pattendaynum");
        hashMap.put("实际出勤天数*","actattendaynum");
        hashMap.put("核算天数*","caldaynum");
    }
}
